<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="btn">1</button>
    <button id="btn2">2</button>
    <script>
      let finallyData;
      let watcher = {
        cleanup: null,
        onChangeExprise: function (fn) {
          if (this.cleanup) {
            this.cleanup();
          }
        },
        saveCleanUp: function (cleanup) {
          this.cleanup = cleanup;
        },
      };
      // function Watcher() {
      //   let cleanup;
      //   return async function get_and_render(time, onChangeExprise) {
      //     let exprise = false;
      //     if (cleanup) {
      //       cleanup();
      //     }
      //     cleanup = () => {
      //       exprise = true;
      //     };
      //     let res = await getData(time);
      //     if (!exprise) {
      //       finallyData = res;
      //     }
      //   };
      // }
      // get_and_render = Watcher();
      function getData(time) {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve(time);
          }, time);
        });
      }
      async function get_and_render(time, onChangeExprise) {
        let exprise = false;
        watcher.onChangeExprise();
        watcher.saveCleanUp(() => {
          exprise = true;
        });
        let res = await getData(time);
        if (!exprise) {
          finallyData = res;
        }
      }
      function pagetion(time) {
        get_and_render(time);
      }
      btn.onclick = () => {
        pagetion(3000);
      };
      btn2.onclick = () => {
        pagetion(2000);
      };
    </script>
  </body>
</html>
